package com.beteng.su.betengsu.ui.fragment.task;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.beteng.su.betengsu.R;
import com.beteng.su.betengsu.adapter.ItemDetailAdapter;
import com.beteng.su.betengsu.base.BaseActivity;
import com.beteng.su.betengsu.bean.BaseBean;
import com.beteng.su.betengsu.bean.OrderBean;
import com.beteng.su.betengsu.bean.OrderTranceBean;
import com.beteng.su.betengsu.bean.SpinnerBean;
import com.beteng.su.betengsu.net.webservice.SiteService;
import com.beteng.su.betengsu.utils.CommonUtils;
import com.beteng.su.betengsu.utils.DateTimeUtils;
import com.beteng.su.betengsu.utils.DensityUtil;
import com.beteng.su.betengsu.widget.AutoToolbar;
import com.beteng.su.betengsu.widget.MyMaterialSpinner;
import com.beteng.su.betengsu.widget.PopSpinnerView;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.PhoneUtils;
import com.blankj.utilcode.util.RegexUtils;
import com.blankj.utilcode.util.SnackbarUtils;
import com.blankj.utilcode.util.StringUtils;
import com.jaredrummler.materialspinner.MaterialSpinner;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.AutoRelativeLayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import czm.statebutton.StateButton;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by chenzhimin on 2017/9/6.
 */

public class ItemDetailActivity extends BaseActivity {
    private static final int INTENT_REQUEST_ADRESS = 10001;
    private static final String SPINNER_MUTIL = "SPINNER_MUTIL";
    private static final String SPINNER_SINGLE = "SPINNER_SINGLE";
    @BindView(R.id.toolbar_back)
    AutoRelativeLayout mToolbarBack;
    @BindView(R.id.toolbar_title)
    TextView mToolbarTitle;
    @BindView(R.id.toolbar)
    AutoToolbar mToolbar;
    @BindView(R.id.item_detail_rv)
    RecyclerView mItemDetailRv;
    @BindView(R.id.info_input_tv_time)
    EditText mInfoInputTvTime;
    @BindView(R.id.nfo_input_spinner)
    MyMaterialSpinner mNfoInputSpinner;
    @BindView(R.id.nfo_input_tv_place)
    EditText mNfoInputTvPlace;
    @BindView(R.id.sign_item_error_plate)
    EditText mSignItemErrorPlate;
    @BindView(R.id.nfo_input_tv_telephone)
    EditText mNfoInputTvTelephone;
    @BindView(R.id.info_input_spinner_remark)
    MyMaterialSpinner mInfoInputSpinnerRemark;
    @BindView(R.id.sign_item_error_remark)
    AppCompatEditText mSignItemErrorRemark;
    @BindView(R.id.btn_commit)
    StateButton mBtnCommit;
    @BindView(R.id.item_detail_top_status_autolinear)
    AutoLinearLayout mAutoLinearlayout;
    @BindView(R.id.item_detail_time_tag)
    TextView mTvTag;
    @BindView(R.id.item_detail_remark_note)
    TextView mTvRemarkNote;


    //判断地点是否必填
    private boolean isPlaceNeed = true;
    //判断车牌是否必填
    private boolean isPlateNoNeed = true;
    //判断手机号是否必填
    private boolean isPhoneNeed = true;
    //判断备注是否能修改
    private boolean isRemarkCanChange = false;




    private final List<SpinnerBean> mSpinnerData = new ArrayList<>();

    private final List<SpinnerBean> mSpinnerReDatas = new ArrayList<>();

    //单个选择进入的order
    private OrderBean mOrderBill;

    //多个选择进入的list
    private ArrayList<OrderBean> mMutilOrderSelect = new ArrayList<>();

    //选择到的目的站点id
    private int mResultID;

    //盘点是单个选择还是多个选择
    private boolean isSingleSelect;
    private ItemDetailAdapter mItemDetailAdapter;


    @Override
    public void initData(Bundle savedInstanceState) {

        mToolbarTitle.setText(getTitle());

         mItemDetailAdapter = new ItemDetailAdapter(context);
        CommonUtils.configRecycleView(mItemDetailRv,new LinearLayoutManager(context));
        mItemDetailRv.setAdapter(mItemDetailAdapter);

        if (OrderInputActivity.SERACH_ITEM_NUTIL_INTENT.equals(getIntent().getAction())) {
            isSingleSelect = false;
            mMutilOrderSelect = getIntent().getParcelableArrayListExtra(OrderInputActivity.SERACH_ITEM_NUTIL_INTENT);
            if (mMutilOrderSelect.size() == 1) {
                isSingleSelect = true;
            }
            mOrderBill = mMutilOrderSelect.get(0);

        } else if (OrderInputActivity.SERACH_ITEM_SINGLE_INTENT.equals(getIntent().getAction())) {
            isSingleSelect = true;
            mOrderBill = getIntent().getParcelableExtra(OrderInputActivity.SERACH_ITEM_SINGLE_INTENT);

        }

        if (mOrderBill != null) {
            mInfoInputTvTime.setText(mOrderBill.getLastUpdateDateTime() + "");
            mNfoInputSpinner.setText(mOrderBill.getTraceStatus() + "");
            mSignItemErrorPlate.setText(mOrderBill.getPlate() + "");
            mInfoInputSpinnerRemark.setText(mOrderBill.getTraceStatusDescrpiton() + "");
        }

        if (!isSingleSelect) {
            mAutoLinearlayout.setVisibility(View.GONE);
            mItemDetailRv.setVisibility(View.GONE);
            initSpinner(SPINNER_MUTIL);
        } else {
            requestTrance();
            initSpinner(SPINNER_SINGLE);
        }


    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_item_detail;
    }

    private void initSpinner(String status) {

        mSpinnerData.clear();
        //多选同一个委托书排除
//        mSpinnerData.add(new SpinnerBean("支线运行", 6));
//        mSpinnerData.add(new SpinnerBean("派送中", 8));
        if (SPINNER_MUTIL.equals(status)) {

            mSpinnerData.add(SpinnerBean.已离开);
            mSpinnerData.add(SpinnerBean.途经);
            mSpinnerData.add(SpinnerBean.首站到达);
            mSpinnerData.add(SpinnerBean.目的站到达);


        } else if (SPINNER_SINGLE.equals(status)) {
            mSpinnerData.add(SpinnerBean.已离开);
            mSpinnerData.add(SpinnerBean.途经);
            mSpinnerData.add(SpinnerBean.首站到达);
            mSpinnerData.add(SpinnerBean.支线运行);
            mSpinnerData.add(SpinnerBean.目的站到达);
            mSpinnerData.add(SpinnerBean.派送中);
        }


        mNfoInputSpinner.setItems(mSpinnerData);

//        mNfoInputSpinner.init(mSpinnerData.size(), DensityUtil.dip2px(this, 180), new PopSpinnerView.NameFilter(){
//
//            @Override
//            public String filter(int position) {
//                return mSpinnerData.get(position).toString();
//            }
//        });



        mSpinnerReDatas.add(SpinnerBean.请选择);
        mSpinnerReDatas.add(SpinnerBean.计划派送);
        mSpinnerReDatas.add(SpinnerBean.计划中转);
        mSpinnerReDatas.add(SpinnerBean.客户未提);
        mSpinnerReDatas.add(SpinnerBean.等客户通知送货);

        mInfoInputSpinnerRemark.setItems(mSpinnerReDatas);

        mInfoInputTvTime.setText(DateTimeUtils.getDateWithFormat("yyyy-MM-dd HH:mm"));
        mInfoInputTvTime.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {

                if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                    LogUtils.e("点击了");
                    new TimePickerDialog.Builder()
                            .setCallBack(new OnDateSetListener() {
                                @Override
                                public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
                                    mInfoInputTvTime.setText(DateTimeUtils.getDateWithFormat("yyyy-MM-dd HH:mm", millseconds));
                                    timePickerView.dismiss();
                                }
                            })
                            .setCancelStringId("取消")
                            .setSureStringId("确定")
                            .setTitleStringId("请选择")
                            .setYearText("年")
                            .setMonthText("月")
                            .setDayText("日")
                            .setHourText("时")
                            .setMinuteText("分")
                            .setCyclic(false)
                            .setThemeColor(getResources().getColor(R.color.timepicker_dialog_bg))
                            .setType(Type.ALL)
                            .setWheelItemTextNormalColor(getResources().getColor(R.color.timetimepicker_default_text_color))
                            .setWheelItemTextSelectorColor(getResources().getColor(R.color.timepicker_toolbar_bg))
                            .setWheelItemTextSize(12)
                            .build()
                            .show(getSupportFragmentManager(), "month_day_hour_minute");
                }

                return true;
            }
        });
    }

    private void requestTrance(){
        showLoading();
        HashMap<String, Object> params = new HashMap<>();
        params.put("SupplierSubCommissionID", mOrderBill != null ? mOrderBill.getSupplierSubCommissionID() : 0);
        SiteService.getInstants().getWaybillTrace(params,context)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<List<OrderTranceBean>>() {
                    @Override
                    public void accept(List<OrderTranceBean> orderTranceBeen) throws Exception {
                        hideLoading();

                        mItemDetailAdapter.setData(orderTranceBeen);

                        mItemDetailAdapter.notifyDataSetChanged();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideLoading();
                        SnackbarUtils.with(mBtnCommit).setMessage(throwable.getMessage()).showWarning();
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);

        if (requestCode == INTENT_REQUEST_ADRESS) {
            if (intent == null) {
                return;
            }
            Bundle bundleExtra = intent.getBundleExtra(AddressChooseActivity.BUNDLE_2);
            mResultID = bundleExtra.getInt(AddressChooseActivity.ID_RESULT);
//            String stringExtra = bundleExtra.getString(AddressChooseActivity.STR_RESULT);
            String stringPurposeName = bundleExtra.getString(AddressChooseActivity.STR_RESULT);
            mNfoInputTvPlace.setText(stringPurposeName);

            LogUtils.d(stringPurposeName);

        }
    }

    @OnClick({R.id.nfo_input_tv_place, R.id.btn_commit, R.id.toolbar_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.nfo_input_tv_place:
                Intent intent = new Intent(this,AddressChooseActivity.class);

                startActivityForResult(intent,INTENT_REQUEST_ADRESS);
                break;
            case R.id.btn_commit:
                commitData();
                break;
            case R.id.toolbar_back:
                finish();
                break;
        }
    }


    private void commitData() {

        if (isSingleSelect&&mOrderBill == null) {
            SnackbarUtils.with(mBtnCommit).setMessage("信息异常请重新进入").showWarning();
            return;
        }else if (!isSingleSelect&&mMutilOrderSelect.size()==0){
            SnackbarUtils.with(mBtnCommit).setMessage("信息异常请重新进入").showWarning();
            return;
        }


        if (isPlaceNeed&& StringUtils.isEmpty(mNfoInputTvPlace.getText().toString().trim())) {
            SnackbarUtils.with(mNfoInputTvPlace).setMessage("地址为必填").showWarning();
            return;
        }

        if(isPlateNoNeed&&StringUtils.isEmpty(mSignItemErrorPlate.getText().toString().trim())){

            SnackbarUtils.with(mNfoInputTvPlace).setMessage("车牌号为必填").showWarning();
            return;
        }

        if(isPhoneNeed&&StringUtils.isEmpty(mNfoInputTvTelephone.getText().toString().trim())){

            SnackbarUtils.with(mNfoInputTvTelephone).setMessage("手机号为必填").showWarning();
            return;
        }

        if (isPhoneNeed&&!RegexUtils.isMobileExact(mNfoInputTvTelephone.getText().toString().trim())) {
            SnackbarUtils.with(mNfoInputTvTelephone).setMessage("输入手机号码不对").showWarning();
            return;
        }


        //
//        if (!RegexUtils.isMobileExact(mNfoInputTvTelephone.getText().toString().trim())) {
//            SnackbarUtils.with(mBtnCommit).setMessage("输入手机号码不对").showWarning();
//            return;
//        }


        HashMap<String, Object> params = new HashMap<>();


        params.put("Status", mSpinnerData.get(mNfoInputSpinner.getSelectedIndex()).getIndex());
        params.put("OccurDateTime", mInfoInputTvTime.getText().toString().trim());
        params.put("AreaID", mResultID);
        params.put("Plate", mSignItemErrorPlate.getText().toString().trim());
        params.put("PhoneNumber", mNfoInputTvTelephone.getText().toString().trim());
        params.put("SupplierDescription", mSignItemErrorRemark.getText().toString().trim());
        params.put("Description", mInfoInputSpinnerRemark.getText().toString().trim());


        JSONArray jsonArray = new JSONArray();
        JSONObject object = new JSONObject();

        for (int i = 0; i < mMutilOrderSelect.size(); i++) {
            object.put("SupplierCommissionID", mMutilOrderSelect.get(i).getSupplierCommissionID());
            object.put("SupplierSubCommissionID", mMutilOrderSelect.get(i).getSupplierSubCommissionID());
            object.put("WaybillID", mMutilOrderSelect.get(i).getWaybillID());
            jsonArray.add(object);
        }

        params.put("WaybillList", jsonArray);

        showLoading();
        SiteService.getInstants().commitOrderInfo(params,context)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<BaseBean>() {
                    @Override
                    public void accept(BaseBean baseBean) throws Exception {
                        showMessageDialog("提交成功");
                        clearDatas();
                        hideLoading();
                        requestTrance();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {

                        hideLoading();
                        LogUtils.e(throwable.getMessage());
                        showMessageDialog(throwable.getMessage());
                    }
                });
    }

    private void clearDatas() {
        mInfoInputSpinnerRemark.setText("已离开");
        mNfoInputTvPlace.setText("");
        mSignItemErrorPlate.setText("");
        mNfoInputTvTelephone.setText("");
        mSignItemErrorRemark.setText("");
        mResultID = 0;
        mInfoInputSpinnerRemark.setClickable(true);
    }

    @Override
    public void setListener() {
        super.setListener();



        mNfoInputSpinner.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener() {
            @Override
            public void onItemSelected(MaterialSpinner view, int position, long id, Object item) {
                if (item instanceof SpinnerBean) {
                    mInfoInputSpinnerRemark.setText("请选择");
                    SpinnerBean spinnerBean = (SpinnerBean) item;
                    if (spinnerBean== SpinnerBean.已离开) {
                        isPlaceNeed = true;
                        isPlateNoNeed = true;
                        isPhoneNeed =true;

                        mInfoInputSpinnerRemark.setClickable(false);
                        mTvRemarkNote.setText("需备注预计到达首站时间");
                        mTvTag.setText("发车时间");
                    }else if (spinnerBean==SpinnerBean.途经){
                        isPlaceNeed = true;
                        isPlateNoNeed = false;
                        isPhoneNeed =false;
                        isRemarkCanChange = false;
                        mTvRemarkNote.setText("");
                        mInfoInputSpinnerRemark.setClickable(false);

                        mTvTag.setText("默认时间");
                    }else if (spinnerBean==SpinnerBean.首站到达){
                        isPlaceNeed = true;
                        isPlateNoNeed = false;
                        isPhoneNeed =false;
                        isRemarkCanChange = false;
                        mTvRemarkNote.setText("如果需要中转需备注预计中转时间");
                        mInfoInputSpinnerRemark.setClickable(false);

                        mTvTag.setText("实际到车时间");
                    }else if (spinnerBean==SpinnerBean.支线运行){

                        mInfoInputSpinnerRemark.setClickable(true);

                        isPlaceNeed = false;
                        isPlateNoNeed = false;
                        isPhoneNeed =false;
                        isRemarkCanChange = true;
                        mTvRemarkNote.setText("需备中转渠道电话及相关单号，及当天预计中转时间");

                        mTvTag.setText("默认时间");
                    }else if (spinnerBean==SpinnerBean.目的站到达){
                        isPlaceNeed = true;
                        isPlateNoNeed = false;
                        isPhoneNeed =false;
                        isRemarkCanChange = false;
                        mTvRemarkNote.setText("需备注派送终端站点联系电话");
                        mInfoInputSpinnerRemark.setClickable(false);

                        mTvTag.setText("实际到车时间");
                    }else if (spinnerBean==SpinnerBean.派送中){
                        isPlaceNeed = false;
                        isPlateNoNeed = false;
                        isPhoneNeed =false;
                        isRemarkCanChange = true;
                        mTvRemarkNote.setText("若备注选择等客户通知放货，需备注清楚客户要求送货时间");
                        mTvTag.setText("默认时间");
                        mInfoInputSpinnerRemark.setClickable(true);
                    }
                }
            }
        });
    }

    private void showMessageDialog(String message) {
        new AlertDialog.Builder(this)
                .setTitle("提示")
                .setMessage(message)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.cancel();
                    }
                }).show();
    }
}
